package com.example.myweb.Controller.Auth;

import com.example.myweb.Common.ApiResponse;
import com.example.myweb.Domain.Entity.User;
import com.example.myweb.Dto.AdminArticleDetailDTO;
import com.example.myweb.Dto.UpdateContentStatusDTO;
import com.example.myweb.Service.Auth.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/admin/articles")
@PreAuthorize("hasRole('ADMIN')") // 只有ADMIN角色的用户才能访问
public class AdminArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 后台获取文章列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<AdminArticleDetailDTO>>> getAllArticles(Pageable pageable) {
        Page<AdminArticleDetailDTO> articlePage = articleService.getAllArticlesForAdmin(pageable);
        return ResponseEntity.ok(ApiResponse.success(articlePage, "后台文章列表获取成功"));
    }

    /**
     * 后台更新文章状态（如隐藏、加精等）
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Void>> updateArticleStatus(
            @PathVariable Long id,
            @Valid @RequestBody UpdateContentStatusDTO request) {
        articleService.updateArticleStatusByAdmin(id, request.getStatus());
        return ResponseEntity.ok(ApiResponse.success("文章状态更新成功"));
    }

    /**
     * 后台删除文章
     */
    @DeleteMapping("/{id}/with-user")
    public ResponseEntity<ApiResponse<Void>> deleteArticleByAdmin(
            @PathVariable Long id,
            @AuthenticationPrincipal User adminUser) { // 也可以获取操作的管理员
        // 注意：这里的 deleteArticle 需要区分用户删除自己的文章还是管理员删除
        // 建议在 ArticleService 中创建一个新的 deleteArticleByAdmin 方法
        articleService.deleteArticle(id, adminUser); // 这里的权限校验逻辑需要调整
        return ResponseEntity.ok(ApiResponse.success("文章删除成功"));
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteArticleByAdmin(@PathVariable Long id) {
        // 调用专门为管理员设计的 service 方法
        articleService.deleteArticleByAdmin(id);
        return ResponseEntity.ok(ApiResponse.success("文章删除成功"));
    }
}
